<template>
  <div
    :class="[
      'message-input',
      {
        active: messageInputActive,
        'add-btn': showNewConversationButton,
      },
    ]"
  >
    <!-- 新增对话按钮 -->
    <div v-if="showNewConversationButton" class="button-w">
      <div class="button">
        <div @click="$emit('createNewConversation')">+ 新增对话</div>
      </div>
    </div>

    <!-- 图片预览区域 -->
    <div v-if="uploadedImages.length > 0" class="image-preview-container">
      <div v-for="(image, index) in uploadedImages" :key="index" class="image-preview-item">
        <img :src="image.url" :alt="image.name" class="preview-image" />
        <div class="image-overlay">
          <span class="image-name">{{ image.name }}</span>
          <el-icon class="remove-icon" @click="removeImage(index)">
            <Close />
          </el-icon>
        </div>
      </div>
    </div>

    <!-- 输入框 -->
    <div class="message-wrap">
      <el-input
        v-model="messageContent"
        :autosize="{ minRows: 2, maxRows: 6 }"
        type="textarea"
        placeholder="输入您想了解的内容"
        @keydown="handleKeyDown"
        @focus="messageInputActive = true"
        @blur="messageInputActive = false"
      />
    </div>

    <!-- 操作按钮区域 -->
    <div class="actions">
      <div class="right">
        <!-- 停止处理按钮 -->
        <el-icon v-if="processing" class="mic" :size="22" @click="$emit('stopProcessing')">
          <SemiSelect />
        </el-icon>
        <!-- 图片上传和发送按钮 -->
        <template v-else>
          <VoiceRecorder @text-recognized="textRecognized" />
          <!-- 图片上传按钮 -->
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="false"
            :accept="acceptedTypes"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :multiple="false"
          >
            <el-icon class="upload-icon" :size="22" @click="handleUploadClick">
              <Picture />
            </el-icon>
          </el-upload>

          <img
            class="sub-img"
            :src="canSend ? activeSendIcon : inactiveSendIcon"
            alt="发送"
            @click="handleSend"
          />
        </template>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, type UploadFile, type UploadRawFile } from 'element-plus'
import { SemiSelect, Picture, Close } from '@element-plus/icons-vue'
import type { ModelOption, ChatImage } from '@/types/chat'

import VoiceRecorder from './VoiceRecorder.vue'

import activeSendIcon from '@/assets/images/active-send-icon.png'
import inactiveSendIcon from '@/assets/images/inactive-send-icon.png'

interface UploadedImage {
  name: string
  url: string
  file: File
  size: number
}

interface Props {
  models: ModelOption[]
  processing?: boolean
  isLogin?: boolean
  showNewConversationButton?: boolean
  maxSize?: number // 最大文件大小，单位MB
  maxCount?: number // 最大上传数量
}

interface Emits {
  (e: 'sendMessage', data: { message: string; images: ChatImage[] }): void
  (e: 'createNewConversation'): void
  (e: 'stopProcessing'): void
  (e: 'modelChange', model: string): void
}

const props = withDefaults(defineProps<Props>(), {
  processing: false,
  isLogin: false,
  showNewConversationButton: false,
  maxSize: 10, // 默认10MB
  maxCount: 5, // 默认最多5张图片
})

const emit = defineEmits<Emits>()

const messageContent = ref('')
const messageInputActive = ref(false)
const uploadRef = ref()
const uploadedImages = ref<UploadedImage[]>([])

// 支持的图片类型
const acceptedTypes = 'image/jpeg,image/jpg,image/png,image/gif,image/webp'

// 计算是否可以发送
const canSend = computed(() => {
  return messageContent.value.trim().length > 0 || uploadedImages.value.length > 0
})

// 文件上传前的检查
const beforeUpload = (rawFile: UploadRawFile) => {
  // 检查文件类型
  const isImage = rawFile.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }

  // 检查文件大小
  const isLtMaxSize = props.maxSize > rawFile.size / 1024 / 1024
  if (!isLtMaxSize) {
    ElMessage.error(`图片大小不能超过 ${props.maxSize}MB!`)
    return false
  }

  // 检查数量限制
  if (uploadedImages.value.length >= props.maxCount) {
    ElMessage.error(`最多只能上传 ${props.maxCount} 张图片!`)
    return false
  }

  return true
}

// 处理文件变化
const handleFileChange = (uploadFile: UploadFile) => {
  if (uploadFile.raw) {
    const file = uploadFile.raw

    // 创建预览URL
    const url = URL.createObjectURL(file)

    const imageData: UploadedImage = {
      name: file.name,
      url: url,
      file: file,
      size: file.size
    }

    uploadedImages.value.push(imageData)
  }
}

// 处理上传按钮点击
const handleUploadClick = () => {
  if (props.processing) {
    ElMessage.warning('当前无法上传图片')
    return
  }

  if (uploadedImages.value.length >= props.maxCount) {
    ElMessage.warning(`最多只能上传 ${props.maxCount} 张图片`)
    return
  }
}

// 移除图片
const removeImage = (index: number) => {
  const image = uploadedImages.value[index]
  // 释放URL对象
  URL.revokeObjectURL(image.url)

  uploadedImages.value.splice(index, 1)
}

// 清空所有图片
const clearImages = () => {
  uploadedImages.value.forEach(image => {
    URL.revokeObjectURL(image.url)
  })
  uploadedImages.value = []
}

// 处理键盘事件
function handleKeyDown(event: KeyboardEvent) {
  if (event.key === 'Enter' && !event.ctrlKey) {
    event.preventDefault()
    handleSend()
  } else if (event.key === 'Enter' && event.ctrlKey) {
    // 按下 Ctrl + Enter 时让文本框正常换行
    messageContent.value += '\n'
    return
  }
}

// 语音输入
function textRecognized(text: string) {
  messageContent.value += text
}

// 处理发送消息
function handleSend() {
  if (!canSend.value) {
    ElMessage.warning('请输入内容或上传图片')
    return
  }

  const messageData = {
    message: messageContent.value.trim(),
    images: uploadedImages.value.map(img => ({
      name: img.name,
      url: img.url,
      file: img.file,
      size: img.size,
    })),
  }

  emit('sendMessage', messageData)

  // 清空输入
  messageContent.value = ''
  clearImages()
}
</script>

<style lang="scss" scoped>
.message-input {
  background: #ffffff;
  box-shadow: 0px 4px 12px 0px rgba(43, 110, 80, 0.1);
  border-radius: 22px;
  border: 1px solid #c4c4cc;
  padding: 10px;
  box-sizing: border-box;
  position: relative;

  &:hover {
    border-color: #2b6e50;
    box-shadow: 0px 4px 8px rgba(11, 73, 149, 0.1);
  }

  &.active {
    border-color: #2b6e50;
    box-shadow: 0px 4px 8px rgba(11, 73, 149, 0.2);
    outline: none;
  }

  :deep(.el-textarea__inner) {
    outline: 0 none;
    border: 0 none;
    box-shadow: none;
  }

  .button-w {
    display: none;
  }

  .image-preview-container {
    margin-bottom: 10px;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .image-preview-item {
      position: relative;
      width: 80px;
      height: 80px;
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #dcdfe6;

      .preview-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .image-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        padding: 4px;
        opacity: 0;
        transition: opacity 0.3s;

        .image-name {
          color: white;
          font-size: 10px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .remove-icon {
          color: white;
          cursor: pointer;
          align-self: flex-end;

          &:hover {
            color: #f56c6c;
          }
        }
      }

      &:hover .image-overlay {
        opacity: 1;
      }
    }
  }

  .actions {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
    margin-top: 10px;

    .models {
      width: 130px;
    }

    .right {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      gap: 6px;

      .mic {
        width: 32px;
        height: 32px;
        background-color: #2b6e50;
        border-radius: 8px;
        color: #fff;
        cursor: pointer;

        &:hover {
          opacity: 0.8;
        }
      }

      .upload-icon {
        width: 32px;
        height: 32px;
        border-radius: 8px;
        color: #19243A;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;

        &:hover {
          opacity: 0.8;
        }
      }

      .sub-img {
        width: 32px;
        height: 32px;
        cursor: pointer;
      }
    }
  }

  :deep(.el-upload) {
    display: inline-block;
  }
}

.add-btn {
  .button-w {
    display: block;
    box-sizing: border-box;
    border: 1px solid transparent;
    border-bottom: 1px solid #fff;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    background-color: #ffffff;

    .button {
      width: 100%;
      padding: 10px 0 12px;
      border-bottom: 1px solid rgba(235, 235, 235, 1);

      div {
        cursor: pointer;
      }
    }
  }
}
</style>
